from django import http
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.shortcuts import render_to_response
from django.utils.html import escape
from forms import CommentForm
import urllib

VERIFY_URL = "http://api-verify.recaptcha.net/verify"
PRIVATE_KEY= "Putyourkeyhere"

def submit_comment(request):
    if request.method != 'POST':
        return http.HttpResponseNotAllowed(["POST"])
    
    data = request.POST.copy()

    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    if ctype is None or object_pk is None:
        return http.HttpBadRequest("Missing content_type or object_pk field.")
    try:
        model = models.get_model(*ctype.split(".", 1))
        target = model._default_manager.get(pk=object_pk)
    except TypeError:
        return http.HttpBadRequest(
            "Invalid content_type value: %r" % escape(ctype))
    except AttributeError:
        return http.HttpBadRequest(
            "The given content-type %r does not resolve to a valid model." % \
                escape(ctype))
    except ObjectDoesNotExist:
        return http.HttpBadRequest(
            "No object matching content-type %r and object PK %r exists." % \
                (escape(ctype), escape(object_pk)))
    
    form = CommentForm(target, data=data)

    u = urllib.urlencode({
    'privatekey': PRIVATE_KEY,
    'remoteip'  : request.META['REMOTE_ADDR'],
    'challenge' : data.get('recaptcha_challenge_field'),
    'response'  : data.get('recaptcha_response_field'),
    })

    f = urllib.urlopen(VERIFY_URL, u)
    captcha_response = f.readlines()

    if form.is_valid() and captcha_response[0].strip()=='true':
        comment = form.get_comment_object()
        comment.save()
    else:
        if captcha_response[1].strip() == 'incorrect-captcha-sol':
            return render_to_response('comments/form.html',{'form':form, \
                                      'captcha_error':'You got captcha wrong!!! Concentrate and try once more.'})
        else:
            if not form.is_valid():
                return render_to_response('comments/form.html',{'form': form})
            return render_to_response('comments/form.html',{'captcha_error': 'You are a spambot. Go to Hell!!!'})
    return http.HttpResponseRedirect('/comments/posted/')

def comment_done(request):
    return render_to_response('comments/posted.html',{})

